package logic

import (
	"api/model/mysql"
	"context"
	"errors"
	"github.com/google/uuid"
	"house_srv/house"
	"house_srv/internal/svc"
	"house_srv/pkg"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateOrderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateOrderLogic {
	return &CreateOrderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateOrderLogic) CreateOrder(in *house.CreateOrderHouseRequest) (*house.CreateOrderHouseResponse, error) {
	// todo: add your logic here and delete this line
	var h mysql.House
	mysql.DB.Debug().Where("id=?", in.HouseId).Find(&h)

	if h.ID == 0 {
		logx.Error("商品不存在")
		return nil, errors.New("商品不存在")
	}
	orderSn := uuid.NewString()
	order := mysql.Order{
		UserId:      int(in.UserId),
		HouseId:     int(in.HouseId),
		OrderSn:     orderSn,
		Pay:         1,
		OrderStatus: 1,
		Amount:      h.HousePrice,
	}

	mysql.DB.Create(&order)

	orderStatus := strconv.FormatFloat(10, 'f', 2, 64)
	url := pkg.Pay(order.OrderSn, orderStatus)

	return &house.CreateOrderHouseResponse{
		Id:  int64(order.ID),
		Url: url,
	}, nil
}
